import { _decorator, Component, director, Node, RigidBody, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('BoardModel')
export class BoardModel extends Component {
    private _model_rigbody: RigidBody
    private _fallRecycleDistance_n: number = 2000
    private _isFall_b: boolean = false
    private _startPosition_v3: Vec3

    /**
     * 当节点回收时调用
     */
    public onRecycle: () => {}

    protected update(dt: number): void {
        // 如果开始下落
        if (this._isFall_b) {
            const selfWorldPosition_v3 = this.node.getWorldPosition().clone()
            const moveDistance_n = this._startPosition_v3.subtract(selfWorldPosition_v3).length()
            // 移动距离 > 下落回收距离 = 开始回收
            if ( moveDistance_n > this._fallRecycleDistance_n) {
                this.recycle()
            }
        }   
    }


    protected start(): void {
        this.init()
    }

    public init() {
        this._model_rigbody = this.getComponent(RigidBody)
        if (!this._model_rigbody) {
            console.error("没添加rigbody")
        }

        this._startPosition_v3 = this.node.getWorldPosition().clone()
    }


    /**
     * 下落
     */
    public fall() {
        // 如果已经下落, 不在调用
        if (this._isFall_b)
            return
        this._isFall_b = true


        // 将节点转移到场景下的GamePlay
        const gamePlay_node = director.getScene().getChildByName("GamePlay")
        const world_v3 = this.node.getWorldPosition().clone()
        const world_quat = this.node.getWorldRotation().clone()
        this._model_rigbody.type = RigidBody.Type.DYNAMIC
        this.node.removeFromParent()
        gamePlay_node.addChild(this.node)
        this.node.setWorldPosition(world_v3)
        this.node.setWorldRotation(world_quat)
    }

    private _isRecycle = false
    /**
     * 回收, 先做销毁处理
     */
    private recycle() {
        // 如果已经下落, 不在调用
        if (this._isRecycle)
            return
        this._isRecycle = true

        if (this.onRecycle) {
            this.onRecycle()
        }
        this.node.destroy()
    }
}